<template>
  <div class="search">
    <i class="iconfont icon-fanhui" @click="goBack()"></i>

    <!-- van-search 组件加上 ref="searchInput" -->
    <van-search ref="searchInput" class="input" v-model="value" show-action placeholder="搜索菜谱" @search="onSearch"
      @focus="showHints = true" @blur="handleBlur" @click="showHints = true" clearable @clear="showHints = true">
      <template #action>
        <div @click="onClickButton">搜索</div>
      </template>
    </van-search>
  </div>

  <commonItem v-if="!showHints" :currentData="data" :isShowAi=true :cookName="value"></commonItem>

  <!-- 提示词区域 -->
  <div v-if="showHints && hints.length > 0" class="hint-container">
    <div v-for="(hint, index) in hints" :key="index" class="hint-item" @click="selectHint(hint)">
      {{ hint }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { useRoute } from 'vue-router'; // 导入 useRoute 和 useRouter
import router from '@/router/index.js';
import { getCookByName } from '@/api/index.js';
import commonItem from '@/components/commonItem.vue';

const value = ref('');
const showHints = ref(false);
const hints = ref(['西红柿炒鸡蛋', '糖醋排骨', '麻婆豆腐', '黄豆烧鸡脚', '宫保鸡丁', '水煮牛肉']);
const searchInput = ref(null);
const data = ref({});

// 恢复上次的搜索结果
const restoreSearchResults = () => {
  const savedResults = sessionStorage.getItem('searchResults');
  const savedValue = sessionStorage.getItem('searchValue');

  if (savedValue !== null) {
    value.value = savedValue;
  }

  if (savedResults) {
    try {
      data.value = JSON.parse(savedResults);
      showHints.value = false;

      // 确保 DOM 更新后再操作 input
      nextTick(() => {
        if (searchInput.value && searchInput.value.$el) {
          const inputElement = searchInput.value.$el.querySelector('input');
          if (inputElement) {
            inputElement.focus();
            inputElement.setSelectionRange(
              inputElement.value.length,
              inputElement.value.length
            );
          }
        }
      });
    } catch (e) {
      console.error('Failed to parse saved search results:', e);
    }
  }
};

// 获取当前路由和路由器实例
const route = useRoute();

// 判断是否从 /detailCook 跳转过来
const shouldRestoreResults = () => {
  const fromRoute = router.options.history.state.back;
  return fromRoute && fromRoute.includes('/detailCook');
};

const onSearch = async (val) => {
  const res = await getCookByName(val);
  if (res) {
    data.value = res.data;
    // 将搜索结果保存到 sessionStorage 中
    sessionStorage.setItem('searchResults', JSON.stringify(data.value));
    sessionStorage.setItem('searchValue', val)
  }
};

const onClickButton = () => {
  onSearch(value.value);
};

const handleBlur = () => {
  setTimeout(() => {
    showHints.value = false;
  }, 200);
};

const selectHint = (hint) => {
  value.value = hint;
  showHints.value = false;
  onSearch(value.value);
};

const goBack = () => {
  router.push({ path: '/home' });
  // 只清除与搜索相关的缓存
  sessionStorage.removeItem('searchResults');
  sessionStorage.removeItem('searchValue');
}

// 页面加载完后聚焦输入框，并尝试根据条件恢复搜索结果
onMounted(() => {
  if (searchInput.value && searchInput.value.$el) {
    const inputElement = searchInput.value.$el.querySelector('input');
    if (inputElement) {
      inputElement.focus();
    }
  }

  // if (shouldRestoreResults()) {
  restoreSearchResults(); // 根据条件决定是否恢复搜索结果
  // }
});
</script>


<style lang="less" scoped>
.search {
  display: flex;
  align-items: center;

  .iconfont {
    margin-left: 4px;
  }

  .input {
    flex: 1;
  }
}

.hint-container {
  display: flex;
  flex-wrap: wrap;
  /* 自动换行 */
  gap: 8px;
  /* 元素之间的间距 */
  padding: 10px;
  border-top: none;
  border: 1px solid #ebedf0;
  background-color: white;
  width: 100%;
  box-sizing: border-box;
  max-height: 150px;
  overflow-y: auto;
}

.hint-item {
  padding: 8px 12px;
  background-color: #c4c5c6;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;

  &:hover {
    background-color: #e9ecef;
  }
}
</style>